<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Util\Err;
use App\Http\Util\Upload;
use App\Models\AllExam;
use App\Models\Answers;
use App\Models\Article;
use App\Models\Contract;
use App\Models\Exam;
use App\Models\Member;
use App\Models\Message;
use App\Models\OperateCate;
use App\Models\OperateChild;
use App\Models\Order;
use App\Models\Paper;
use App\Models\Question;
use App\Models\QuestionCategory;
use App\Models\Service;
use App\Models\ServiceCategory;
use App\Models\Sign;
use App\Models\Study;
use App\Models\StudyCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class StaticsController extends Controller
{
    /**首页滚动数据
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function scrollNum(Request $request)
    {
//        $key = 'VIEW_COUNT_ALL';
//        $data['views'] = Redis::get($key) ? (int)Redis::get($key) : 0;
        $data['members'] = Member::count();
        $data['contracts'] =Contract::where('is_del',Err::DEL_SHOW)->count();
        $data['orders'] = Order::where('status',1)->count();
        $data['vips'] =Member::where('is_vip',1)->where('vip_time','>',time())->count();
        return response()->json(['code' => 200, 'data' => $data, 'msg' => 'ok']);
    }

    /**获取linechart
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function chartData(Request $request){
        $monday =  date('Y-m-d',strtotime('-1 week last monday'));
        $time = strtotime($monday);
        $data =[];
        for($i=0;$i<7;$i++){
            $key=date("Y-m-d", strtotime("+{$i} day", $time)).'MONEY_COUNT';
            $value = Redis::get($key)?Redis::get($key):0;
            $data['expectedData'][] =sprintf("%01.2f",$value/100);
        }
        return response()->json(['code' => 200, 'data' => $data, 'msg' => 'ok']);
    }

    /**获取piechart
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function pieData(Request $request){
        $data['pieChart'][]  = '微信用户';
        $data['pieChart'][] = '手机用户';
        $data['pieChartData'] =[];
//        $array= QuestionCategory::where('is_del',Err::DEL_SHOW)->get(['id','name']);
//        foreach($array as $k => $v){
//           $data['pieChart'][] =$v['name'];
//           $data['pieChartData'][$k]['name'] = $v['name'];
//           $data['pieChartData'][$k]['value']  = Question::where('is_del',Err::DEL_SHOW)
//               ->where('cate_id',$v['id'])->count();
//        }

        $wxArr['name'] = '微信用户';
        $wxArr['value'] = Member::where('Login_type',Err::MEMBER_LOGIN_WECHAT)->count();
        $mbArr['name'] = '手机用户';
        $mbArr['value'] =  Member::where('Login_type',Err::MEMBER_LOGIN_MOBILE)->count();
        array_push($data['pieChartData'],$wxArr);
        array_push($data['pieChartData'],$mbArr);
        return response()->json(['code' => 200, 'data' => $data, 'msg' => 'ok']);
    }

    public function pieData1(Request $request){
        $data['pieChart'] = [];
        $data['pieChartData'] =[];
        $array= ServiceCategory::where('is_del',Err::DEL_SHOW)->get(['id','name']);
        foreach($array as $k => $v){
            $data['pieChart'][] =$v['name'];
            $data['pieChartData'][$k]['name'] = $v['name'];
            $data['pieChartData'][$k]['value']  = Service::where('is_del',Err::DEL_SHOW)
                ->where('cate_id',$v['id'])->count();
        }
        return response()->json(['code' => 200, 'data' => $data, 'msg' => 'ok']);
    }

    /**本周计划保存
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function save_todo(Request $request)
    {
        try {
            $data = $request->post();
            $expired = date('Y-m-d H:i:s', strtotime('+1 week last monday'));
            $expired = strtotime($expired) - time();
            if (Redis::setex('to_do_array', $expired, json_encode($data))) {
                return response()->json(['code' => 200, 'msg' => 'ok']);
            } else {
                return response()->json(['code' => 1001, 'msg' => 'error']);
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }

    /**获取本周计划
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_todo(Request $request)
    {
        try {
            $data = Redis::get('to_do_array');
            $data = json_decode($data);
            return response()->json(['code' => 200, 'msg' => 'ok', 'data' => $data]);
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }

    /**获取月数据
     * @param Request $request
     * @return mixed
     */
    public function month_data(Request $request){
        try{

            $data['line'] = [];
            $data['data'] =[];
            $limit = 20;
            $count = Redis::zcard('SEARCH_RANK_LIST');
            $list = Redis::zrevrange('SEARCH_RANK_LIST',0,$limit-1,array('withscores'=>true));
            foreach($list as $k => $v){
                array_push($data['line'],$k);
                $data['data'][] = $v;
            }
//            for($i=1;$i<=12;$i++){
//                if($i<10){
//                    $start= date("Y-0{$i}-01 00:00:00");
//                    $end= date("Y-0".($i+1)."-01 00:00:00");
//                }else{
//                    $start= date("Y-{$i}-01 00:00:00");
//                    $end= date("Y-".($i+1)."-01 00:00:00");
//                }
//                array_push($data['line'],"{$i}月");
//                $data['data'][] = rand(1,100);
//            }
            return response()->json(['code' => 200, 'msg' => 'ok', 'data' => $data]);
        }catch (\Exception $e){
            echo $e->getMessage();
        }
    }


    public function month_data_user(Request $request){
//        try{
            $data['line'] = [];
            $data['data'] =[];
            for($i=0;$i<7;$i++){
                $date = date("Y-m-d",strtotime("-{$i} day"));
                $start = $date.' 00:00:00';
                $end = $date.' 23:59:59';
                array_push($data['line'],$date);
                $data['data'][] = Member::where(function ($query) use ($start,$end) {
                        $query->where('created_at','>=',$start);
                        $query->where('created_at','<=',$end);
                })->count();
            }
            return response()->json(['code' => 200, 'msg' => 'ok', 'data' => $data]);
//        }catch (\Exception $e){
//            echo $e->getMessage();
//        }
    }

    /**获取通过率
     * @param Request $request
     * @return mixed
     */
    public function passing(Request $request){
        try{
            $post= $request->post('data');
            if($post){
                $where[] = ['search_time','>=',$post[0]];
                $where[] = ['search_time','<=',$post[1]];
            }else{
                $where = [];
            }
                $where[] =['is_del',Err::DEL_SHOW];
            $exams = Exam::where($where)->select('id','name','paper_id')->get()->toArray();
            $data['line'] = [];
            $data['data'] = [];
            $data['avg'] = [];
            foreach($exams as $k => $v){
                $data['line'][] = $v['name'];
                $paper_score = Paper::where('id',$v['paper_id'])->value('pass_score');
                $all_count =Answers::where('exam_id',$v['id'])
                    ->where('is_del',Err::DEL_SHOW)->count();
                $pass_count =Answers::where('score','>=',$paper_score)
                    ->where('exam_id',$v['id'])
                    ->where('is_del',Err::DEL_SHOW)->count();
                $avg= Answers::where('score','>=',$paper_score)
                    ->where('exam_id',$v['id'])
                    ->where('is_del',Err::DEL_SHOW)->avg('score');
                $data['avg'][] = round($avg,2);
                $data['data'][] = $pass_count>0 ?round(($pass_count/$all_count)*100):0;
            }
            return response()->json(['code' => 200, 'msg' => 'ok', 'data' => $data]);
        }catch (\Exception $e){
                echo $e->getMessage();
        }
    }


}
